import Sortable from 'sortablejs'
import storage from '@/utils/storageDrop'
// import fetchData from '@/services/fetch'
import DateFormat from '@/utils/dateUtil.js'
// import { getItem } from '@/utils/storageParms'
// import { getlastMonth, getNowdate } from '@/utils/help'
// 导出工具
import { Loading } from 'element-ui'
// import doExport from '@/utils/excel'
import { json2excel } from '@/utils/setMethods.js'
export const VxeListMixin = {
  data() {
    return {
      // 表格最终高度
      NoEtdFlag: false,
      tableHei: 0,
      exportPageSize: 100000,
      exportLoading: false,
      lazyLoading: false, // 懒加载默认不进行  true不加载数据，存储列表字段   false加载数据，不存储列表字段
      excelDatas: [],
      params: {
        page: 1,
        pageSize: 20,
        orderBy: 'id desc',
        totalRows: 0,
        export: false,
        queryParamList: []
      },
      sortable2: null,
      gridOptions: {
        border: true,
        // 是否可调整
        resizable: true,
        keepSource: true,
        showOverflow: true,
        columnKey: true,
        class: 'sortable-column-demo',
        scrollX: {
          enabled: false
        },
        tooltipConfig: {
          showAll: true
        },
        editRules: {},
        // height: 530,
        loading: false,
        // columnConfig: {
        //   resizable: false
        // },
        // 表格列设置，禁止部分字段筛选
        customConfig: {
          storage: false,
          checkMethod: null,
          allowResizable: false
        },
        rowConfig: {
          isCurrent: true,
          isHover: true
        },
        pagerConfig: {
          total: 1,
          currentPage: 1,
          pageSize: parseInt(20),
          pageSizes: [10, 20, 50, 100, 200, 500]
        },
        editConfig: {
          // 设置触发编辑为点击模式
          trigger: 'click',
          // 设置触发编辑为手动模式
          // trigger: 'manual',
          // 设置为整行编辑模式
          mode: 'row',
          // 显示修改状态和新增状态
          showStatus: true,
          // 自定义可编辑列头的图标
          icon: 'fa fa-file-text-o',
          activeMethod: this.activeCellMethod
        },
        columns: [],
        data: [],
        footerMethod: null,
        checkColumnMethod: null
      },
      tableToolbar: {
        perfect: true,
        refresh: false,
        zoom: false, // 关闭全屏操作
        custom: true,
        slots: {
          buttons: 'toolbar_title'
        }
      },
      sexList1: [
        { value: '1', label: '男' },
        { value: '0', label: '女' }
      ],
      formHidden: false
    }
  },
  watch: {
    $route(to, from) {
      this.tableHeightFun()
    }
  },
  mounted() {
    this.tableHeightFun()
    window.addEventListener('resize', this.tableHeightFun)

    // this.columnDropGrid()

    // this.rowDrop()
    // this.columnDropTable()
  },
  destroyed() {
    window.onresize = null
  },
  created() {
    this.query()
    // if (this.lazyLoading && getItem(`${this.$route.name}_params`)) {
    //   this.params = JSON.parse(getItem(`${this.$route.name}_params`))
    //   this.query()
    // } else {
    //   if (!this.NoEtdFlag) {
    //     this.ETDfun()
    //   }
    // }
    // // 仅缓存模块列表columns
    // if (this.lazyLoading && storage.get(`${this.$route.name}_coumns`)) {
    //   this.columns = storage.get(`${this.$route.name}_coumns`)
    // }
  },
  beforeDestroy() {
    if (this.sortable2) {
      this.sortable2.destroy()
    }
  },
  methods: {
    // ETDfun() {
    //   if (this.params.queryParamList) {
    //     this.params.queryParamList.forEach((e) => {
    //       if (e.field.indexOf('etd') > -1) {
    //         e.items = [getlastMonth(), getNowdate()]
    //       }
    //     })
    //   }
    // },
    // 字典转义  字典列表，值
    formatterCode(data, value) {
      if (value == null || value === undefined) {
        return ''
      }
      const item = data.find(item => item.code === value)
      if (item) {
        return item.name
      }
      return ''
    },
    // 控制隐藏搜索表单显隐
    moreForm() {
      this.formHidden = !this.formHidden
      this.tableHeightFun()
    },
    tableHeightFun() {
      const contentHei = window.innerHeight // 内容区域的高度
      this.$nextTick(() => {
        this.tableHei = contentHei - this.tableHeight + 'px'
        // if (this.$refs.filtersArea && this.$refs.filtersArea.offsetHeight) {
        //   const searchFormHei = this.$refs.filtersArea.offsetHeight // 搜索表单的高度
        //   searchFormHei ? (this.oldTableHei = searchFormHei) : null
        //   this.tableHei = contentHei - this.oldTableHei
        //   if (this.tableHeight != null) {
        //     this.tableHei = this.tableHei - this.tableHeight
        //   } else {
        //     this.tableHei = this.tableHei - 200
        //   }
        //   // 拼接单位
        //   this.tableHei = this.tableHei + 'px'
        // }
      })
    },
    clearForm(form) {
      if (form) {
        Object.keys(form).forEach(
          key => form[key] = form[key] && form[key] instanceof Array ? [] : null
        )
      }
    },
    async clear(callBackFn) {
      this.initParams()
      // 清空
      // this.$refs[form].resetFields()
      // for (const it of this.params.queryParamList) {
      //   if (!it.persistent || !(it.field.indexOf('etd') > -1)) { // 默认查询条件，不让被清空 persistent 持久属性也不会清除
      //     it.value = ''
      //     it.items = []
      //     it.item = ''
      //   } else {
      //     if (!this.NoEtdFlag) {
      //       this.ETDfun()
      //     }
      //   }
      // }
      await this.query()
      // storage.remove(this.url.query)
    },
    initTableData(url, params, callBackFn) {
      this.getTableData(params, null, callBackFn)
    },
    async query(callBackFn) {
      this.params.page = this.params.page ? this.params.page : 1
      await this.getTableData(this.params, 'post', res => {
        if (typeof callBackFn === 'function') {
          callBackFn(res)
        }
      })
    },
    getPages(page, pageSize) {
      // 获取翻页数据
      this.params.page = page
      this.params.pageSize = pageSize
      this.getTableData(this.params)
    },
    async getTableData(params, contentType, callBackFn) {
      if (this.url == null || this.url.query == null || this.url.query === undefined || this.url.query === '') {
        return
      }
      // 获取表格数据
      this.gridOptions.loading = true
      await this.$fetchData(this.url.query, params, 'post')
        .then(res => {
          this.gridOptions.loading = false
          this.gridOptions.pagerConfig.total = res.total
          this.gridOptions.pagerConfig.currentPage = res.currentPage
          this.gridOptions.data = res.data
          if (typeof callBackFn === 'function') {
            callBackFn(res)
          }
          // 接口名加请求参数MD5
          // storage.set(this.url.query, this.gridOptions.data)
        }).catch(error => {
          console.log(error)
          this.gridOptions.loading = false
        })
    },
    formatSex(value) {
      if (value === '1') {
        return '男'
      }
      if (value === '0') {
        return '女'
      }
      return ''
    },
    activeCellMethod({ column, columnIndex }) {
      if (columnIndex === 1) {
        return false
      }
      return true
    },
    editDisabledEvent({ row, column }) {
      console.log('禁止编辑')
    },
    searchEvent() {
      this.gridOptions.pagerConfig.currentPage = 1
      this.params.page = 1
      this.getTableData(this.params)
    },
    handlePageChange({ currentPage, pageSize }) {
      this.gridOptions.pagerConfig.currentPage = currentPage
      this.gridOptions.pagerConfig.pageSize = pageSize
      this.params.page = currentPage
      this.params.pageSize = pageSize
      this.getTableData(this.params)
    },
    editRowEvent(row) {
      const $grid = this.$refs.xGrid
      $grid.setActiveRow(row)
    },
    saveRowEvent() {
      const $grid = this.$refs.xGrid
      $grid.clearActived().then(() => {
        this.gridOptions.loading = true
        setTimeout(() => {
          this.gridOptions.loading = false
          this.$printMsg('保存成功！', 'success')
        }, 300)
      })
    },
    async removeRowEvent(row, rowIndex) {
      const that = this
      that
        .$confirm('您确定要删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          var id = this.gridOptions.data[rowIndex].id
          that.$fetchData(that.url.delete + '/' + id, null, 'delete').then(res => {
            that.loading = false
            if (res) {
              this.$printMsg('删除成功', 'success')
              const $grid = this.$refs.xGrid
              $grid.remove(row)
            }
          })
        })
        .catch(() => {
          that.loading = false
          // 点击取消
          this.$printMsg('已取消', 'info')
        })
    },
    btnVisiable(btnKey) {
      const allMenu = this.$store.getters.allMenus
      // console.log('allMenu')
      // console.log(allMenu)
      //
      for (let i = 0; i < allMenu.length; i++) {
        if (allMenu[i].url === btnKey) {
          if (allMenu[i].isShow === 1) {
            return true
          } else {
            return false
          }
        }
      }
      return false
    },
    rowDrop() {
      this.$nextTick(() => {
        if (this.$refs.xTable === undefined || this.$refs.xTable.$el === undefined) {
          return
        }
        const xTable = this.$refs.xTable
        if (xTable) {
          this.sortable1 = Sortable.create(
            xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'),
            {
              handle: '.drag-btn',
              onEnd: ({ newIndex, oldIndex }) => {
                const currRow = this.tableData.splice(oldIndex, 1)[0]
                this.tableData.splice(newIndex, 0, currRow)
              }
            }
          )
        }
      })
    },
    // 列拖拽
    columnDropTable() {
      this.$nextTick(() => {
        if (this.$refs.xTable === undefined || this.$refs.xTable.$el === undefined) {
          return
        }
        const $table = this.$refs.xTable
        var arr = this.columns
        if (this.lazyLoading) {
          storage.set(`${this.$route.name}_coumns`, arr)
        }
        if ($table) {
          this.sortable2 = Sortable.create(
            $table.$el.querySelector(
              '.body--wrapper>.vxe-table--header .vxe-header--row'
            ),
            {
              handle: '.vxe-header--column:not(.col--fixed)',
              onEnd: ({ item, newIndex, oldIndex }) => {
                const { fullColumn, tableColumn } = $table.getTableColumn()
                const targetThElem = item
                const wrapperElem = targetThElem.parentNode
                const newColumn = fullColumn[newIndex]
                if (newColumn.fixed) {
                  // 错误的移动
                  if (newIndex > oldIndex) {
                    wrapperElem.insertBefore(
                      targetThElem,
                      wrapperElem.children[oldIndex]
                    )
                  } else {
                    wrapperElem.insertBefore(
                      wrapperElem.children[oldIndex],
                      targetThElem
                    )
                  }
                  return this.$XModal.message({
                    content: '固定列不允许拖动！',
                    status: 'error'
                  })
                }
                // 转换真实索引
                const oldColumnIndex = $table.getColumnIndex(
                  tableColumn[oldIndex]
                )
                const newColumnIndex = $table.getColumnIndex(
                  tableColumn[newIndex]
                )
                // 移动到目标列
                const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
                fullColumn.splice(newColumnIndex, 0, currRow)
                $table.loadColumn(fullColumn)

                // 缓存列数据
                if (this.lazyLoading) {
                  arr = storage.get(`${this.$route.name}_coumns`)
                  const oldtableColumnIndex = arr.findIndex((item) => item.field === tableColumn[oldIndex].property)
                  const newtableColumnIndex = (arr || []).findIndex((item) => item.field === tableColumn[newIndex].property)
                  const currRow_ = arr.splice(oldtableColumnIndex, 1)[0]
                  arr.splice(newtableColumnIndex, 0, currRow_)
                  storage.set(`${this.$route.name}_coumns`, arr)
                }
              }
            }
          )
        }
      })
    },
    columnDropGrid() {
      this.$nextTick(() => {
        if (this.$refs.xGrid === undefined || this.$refs.xGrid.$el === undefined) {
          return
        }
        const $table = this.$refs.xGrid
        this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
          handle: '.vxe-header--column:not(.col--fixed)',
          onEnd: ({ item, newIndex, oldIndex }) => {
            const { fullColumn, tableColumn } = $table.getTableColumn()
            const targetThElem = item
            const wrapperElem = targetThElem.parentNode
            const newColumn = fullColumn[newIndex]
            if (newColumn.fixed) {
              // 错误的移动
              if (newIndex > oldIndex) {
                wrapperElem.insertBefore(targetThElem, wrapperElem.children[oldIndex])
              } else {
                wrapperElem.insertBefore(wrapperElem.children[oldIndex], targetThElem)
              }
              return this.$XModal.message({ content: '固定列不允许拖动！', status: 'error' })
            }
            // 转换真实索引
            const oldColumnIndex = $table.getColumnIndex(tableColumn[oldIndex])
            const newColumnIndex = $table.getColumnIndex(tableColumn[newIndex])

            // 移动到目标列
            const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
            fullColumn.splice(newColumnIndex, 0, currRow)

            const arr = this.columns
            // let arr = []
            // if (storage.get(this.$route.name)) {
            //   arr = storage.get(this.$route.name)
            // } else {
            //   arr = this.columns
            // }
            const oldtableColumnIndex = arr.findIndex((item) => item.field === tableColumn[oldIndex].property)
            const newtableColumnIndex = (arr || []).findIndex((item) => item.field === tableColumn[newIndex].property)

            const currRow_ = arr.splice(oldtableColumnIndex, 1)[0]
            arr.splice(newtableColumnIndex, 0, currRow_)
            // storage.set(this.$route.name, arr)

            $table.loadColumn(fullColumn)
          }
        })
      })
    },
    // 导出
    exportXls(fileName) {
      this.excelDatas = []
      // 计算批次
      var total = this.gridOptions.pagerConfig.total
      if (total > 0) {
        this.$confirm('确定要导出列表数据？', '提示')
          .then((res) => {
            const loadingInstance = Loading.service({
              text: '导出准备中，请稍等...'
            })
            const exportConfigArr = []
            for (let i = 0; i < total; i = i + this.exportPageSize) {
              exportConfigArr.push({
                startIndex: i,
                endIndex: i + this.exportPageSize
              })
            }
            // 准备columns数据
            var columns = this.gridOptions.columns.map((x) => {
              if (x.slots !== undefined && x.slots.default === 'operate') {
                return
              } else {
                var item = {
                  label: x.title,
                  prop: x.field,
                  align: 'center'
                }
                return item
              }
            }).filter(item => item !== undefined)
            this.exportData(fileName + '-' + DateFormat.format(new Date(), 'yyyy-MM-dd'), columns, 1, exportConfigArr.length, loadingInstance)
          })
          .catch((error) => {
            console.log(error)
          })
      } else {
        this.$message.error('当前无可导出数据!')
      }
    },
    // 导出数据
    exportData(fileName, columns, index, totalPage, loadingInstance) {
      if (index > totalPage) {
        json2excel(this.excelDatas, fileName, true, 'xlsx')
        // loadingInstance.close()
        this.$message.success('导出完成！')
      } else {
        // loadingInstance.close()
        // if (index === 1) {
        //   loadingInstance = Loading.service({
        //     text:
        //       '正在导出数据，总共会导出' +
        //       totalPage +
        //       '个文件，当前执行第' +
        //       index +
        //       '个导出,请耐心等待...'
        //   })
        // }
        delete this.params.page
        delete this.params.pageSize

        let query = {
          page: index,
          pageSize: this.exportPageSize,
          orderBy: this.params.orderBy,
          totalRows: this.params.totalRows,
          export: false
        }

        query = Object.assign(this.params, query)
        this.$fetchData(this.url.query, query, 'post')
          .then(res => {
            // const name = fileName
            // const timestamp = new Date().getTime()
            // doExport(res, columns, name + timestamp + '_' + index)

            // 数据字典翻译
            // res.content = this.dataFormatter(res.data)

            this.excelDatas.push(
              {
                tHeader: columns.map((item) => item.label), // sheet表一头部
                filterVal: columns.map((item) => item.prop), // 表一的数据字段
                tableDatas: res.data, // 表一的整体json数据
                sheetName: 'sheet' + index// 表一的sheet名字
              }
            )
            // this.exportLog(res.content, fileName)
            this.exportData(fileName, columns, index + 1, totalPage, loadingInstance)
            loadingInstance.close()
          }).catch(error => {
            this.$nextTick(() => {
              this.exportLoading = false
              if (error.error === 'Gateway Timeout') {
                this.$message.error('导出失败,网关超时')
              }
              loadingInstance.close()
            })
            console.log('导出失败', error)
          })
      }
    },
    // 数据翻译
    dataFormatter(data) {
      // 数据字典翻译
      if (this.url.query === this.$api.MpTmsContainerAction.query1) {
        data.forEach(item => {
          if (item.msdcFlag != null && item.msdcFlag === 1) {
            item.msdcFlag = '美设订舱'
          } else {
            item.msdcFlag = '客户自订舱'
          }
          if (item.nzFlag != null && item.nzFlag === 1) {
            item.nzFlag = '是'
          } else {
            item.nzFlag = '否'
          }
          if (item.mdFlag != null && item.mdFlag === 1) {
            item.mdFlag = '是'
          } else {
            item.mdFlag = '否'
          }
          if (item.fhFlag != null && item.fhFlag === 1) {
            item.fhFlag = '是'
          } else {
            item.fhFlag = '否'
          }
          if (item.bhFlag != null && item.bhFlag === 1) {
            item.bhFlag = '是'
          } else {
            item.bhFlag = '否'
          }
        })
      }
      if (this.url.query === this.$api.MpTmsExpressController.query) {
        data.forEach(item => {
          if (item.dayPiece != null && parseInt(item.dayPiece) === 1) {
            item.dayPiece = '是'
          } else {
            item.dayPiece = '否'
          }
        })
      }
      return data
    },
    // 导出履历
    exportLog(res, fileName) {
      const fileUpload = {
        workType: fileName.slice(0, fileName.length - 10),
        parametersIn: JSON.stringify(this.params.queryParamList),
        content: JSON.stringify(res)
      }
      this.$fetchData(this.$api.files.addUpload, fileUpload, 'POST')
        .then((res) => {
          console.log('导出履历记录成功!!!')
        }).catch((err) => {
          console.log('导出履历记录失败，原因为：' + err)
        })
    }

  }
}
